<template>
  <div class="app-container">
    <el-card style="border-radius: 10px">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="transferCode">
        <el-input
          v-model="queryParams.transferCode"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="移入仓库" prop="toWarehouseName">
        <el-input
          v-model="queryParams.toWarehouseName"
          placeholder="请输入移入仓库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="单据日期" prop="transferDate">
        <el-date-picker clearable
                        v-model="queryParams.transferDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>-->
      <el-form-item label="单据日期" prop="params">
        <el-date-picker
            clearable
            v-model="queryParams.params"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            placeholder="请选择入库日期">
        </el-date-picker>
      </el-form-item>

<!--      <el-form-item label="销售订单编号" prop="salesOrderCode">
        <el-input
          v-model="queryParams.salesOrderCode"
          placeholder="请输入销售订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
<!--      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->

<!--      <el-form-item label="产品名称" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height: 15px"></div>
    <el-card style="border-radius: 10px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['wm:transferclient:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wm:transferclient:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wm:transferclient:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wm:transferclient:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="transferclientList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据编号" align="center" prop="transferCode" >
        <template slot-scope="scope">
          <el-button
              type="text"
              @click="handleView(scope.row)"
              v-hasPermi="['wm:transferclient:query']"
          >{{scope.row.transferCode}}</el-button>
        </template>
      </el-table-column>

      <el-table-column label="单据名称" align="center" prop="transferName" />
      <el-table-column label="单据日期" align="center" prop="transferDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.transferDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="移入仓库名称" align="center" prop="toWarehouseName" />
      <el-table-column label="销售订单" align="center" prop="salesOrderCode" />
      <el-table-column label="订单产品" align="center" prop="itemName" />
      <el-table-column label="客户名称" align="center" prop="clientName" />
      <el-table-column label="操作人" align="center" prop="createByName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            v-if="(scope.row.status =='PREPARE')"
            @click="handleExecute(scope.row)"
            v-hasPermi="['wm:transferclient:execute']"
          >执行</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="(scope.row.status =='PREPARE')"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wm:transferclient:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-if="(scope.row.status =='PREPARE')"
            @click="handleDelete(scope.row)"
            v-hasPermi="['wm:transferclient:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改客户调拨对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="单据编号" prop="transferCode" >
              <el-input v-model="form.transferCode" placeholder="请输入单据编号" :disabled="optType != 'add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据名称" prop="transferName">
              <el-input v-model="form.transferName" placeholder="请输入单据名称" :disabled="optType != 'add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据日期" prop="transferDate">
              <el-date-picker clearable
                              v-model="form.transferDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :default-value="new Date()"
                              placeholder="请选择单据日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
<!--              <el-input v-model="form.toWarehouseId" placeholder="请输入移入仓库ID" />-->
              <el-form-item label="接收仓库" prop="toWarehouseId">
                <el-cascader v-model="warehouseInfo" :disabled="optType != 'add'"
                             ref="warehouseRef"
                             :options="warehouseOptions"
                             :props="warehouseProps"
                             style="width:100%"
                             @change="handleWarehouseChanged"
                >
                </el-cascader>
              </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户" prop="clientId">
<!--              <el-input v-model="form.clientId" placeholder="请输入客户id" />-->
              <el-input v-model="form.clientName" placeholder="请输入客户名称" readonly>
                <el-button
                    slot="append"
                    @click="handleSelectClient"
                    icon="el-icon-search"
                    v-if="optType === 'add'"
                >
                </el-button>
              </el-input>
              <ClientSelect ref="clientSelect" @onSelected="onClientSelected" > </ClientSelect>
            </el-form-item>

          </el-col>
          <el-col :span="8">
            <el-form-item label="销售订单" prop="salesOrderCode">
              <el-input v-model="form.salesOrderCode" placeholder="请输入销售订单" readonly >
                <el-button slot="append" v-if="optType == 'add'" icon="el-icon-search" @click="handleOrderSelect" ></el-button>
              </el-input>
              <order-line  ref="orderSelect" v-if="form.clientId" :status="orderQuery" :client-id="form.clientId"  @onSelected="onOrderSelected"></order-line>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品" prop="item">
              <el-input v-model="form.itemName" placeholder="请输入产品" :disabled="optType != 'add'"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="承运商" prop="carrier">
              <el-input v-model="form.carrier" placeholder="请输入承运商" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="承运单号" prop="bookingNote">
              <el-input v-model="form.bookingNote" placeholder="请输入承运单号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="车牌号" prop="carNumber">
              <el-input v-model="form.carNumber" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="客户地址" prop="clientAddress">
              <el-input v-model="form.clientAddress" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="form.transferId !=null" content-position="center">物料信息</el-divider>
      <el-card shadow="always" v-if="form.transferId !=null" class="box-card">
        <TransferClientine ref=line :transferId="form.transferId" :order-code="form.salesOrderCode" :to-ware-loaction-area-info="toWareLoactionAreaInfo" :optType="optType"></TransferClientine>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTransferclient, getTransferclient, delTransferclient, addTransferclient, updateTransferclient,execute } from "@/api/mes/wm/transferclient";
import {genCode} from "@/api/system/autocode/rule";
import OrderLine from "@/components/orderSelect/orderlinesingle"
import OrderSelect from "@/components/orderSelect/single.vue";
import {getTreeList} from "@/api/mes/wm/warehouse";
import ClientSelect from "@/components/clientSelect/single.vue";
import TransferClientine from "@/views/mes/wm/transferclient/line.vue";
import {getTransfer} from "@/api/mes/wm/transfer";


export default {
  name: "Transferclient",
  dicts: ['mes_order_status'],
  components:{TransferClientine, ClientSelect, OrderSelect, OrderLine},
  data() {
    return {
      toWareLoactionAreaInfo:null,
      warehouseCode: 'XBK_VIRTUAL', //线边库
      warehouseInfo: [],
      warehouseOptions: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      optType:undefined,
      orderQuery: '已审批',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户调拨表格数据
      transferclientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        transferCode: null,        transferName: null,        transferType: null,        salesOrderId: null,        salesOrderCode: null,
        salesOrderLineId: null,        clientId: null,        clientCode: null,        clientName: null,
        itemId: null,        itemCode: null,        itemName: null,        carrier: null,        bookingNote: null,
        carNumber: null,        clientAddress: null,
        toWarehouseId: null,        toWarehouseCode: null,        toWarehouseName: null,        transferDate: null,        status: null,
        createByName: null,  params: [],    },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        transferCode: [
          { required: true, message: "单据编号不能为空", trigger: "blur" }
        ],

        transferDate: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
        toWarehouseId: [
          { required: true, message: "接收仓库不能为空", trigger: "blur" }
        ],
        clientId: [
          { required: true, message: "客户不能为空", trigger: "blur" }
        ],
        salesOrderCode: [
          { required: true, message: "销售订单不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseList()
  },
  methods: {
    /** 查询客户调拨列表 */
    getList() {
      this.loading = true;
      const query = { ...this.queryParams };
      if (query.params && query.params.length === 2) {
        query.params = {
          beginTime: query.params[0],
          endTime: query.params[1]
        };
      } else {
        query.params = null;
      }
      listTransferclient(query).then(response => {
        this.transferclientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 查询明细按钮操作
    handleView(row){
      this.reset();
      const transferId = row.transferId
      getTransferclient(transferId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看客户单信息";
        this.optType = "view";
      });
    },
    //执行转移
    handleExecute(row){
      const transferIds = row.transferId;
      this.$modal.confirm('确认执行转移？').then(function() {
        return execute(transferIds)//执行转移
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("转移成功");
      }).catch(() => {});
    },
    // 选择客户
    handleSelectClient(){
      this.$refs.clientSelect.showFlag = true;
    },
    //客户选择弹出框
    onClientSelected(obj){
      if(obj != undefined && obj != null){
        this.form.clientId = obj.clientId;
        this.form.clientCode = obj.clientCode;
        this.form.clientName = obj.clientName;
        this.form.clientAddress=obj.address
      }
    },
    // 选择订单
    handleOrderSelect(){
      if(this.form.clientId){
        this.$refs.orderSelect.showFlag = true;
      }else{
        this.$modal.msgWarning("请先选择客户");
      }

    },
    onOrderSelected(obj){
      if(obj != undefined && obj != null){
        console.log("11111",obj)
        this.form.salesOrderId = obj.soId;
        this.form.salesOrderCode=obj.soNumber;
        this.form.salesOrderLineId=obj.lineId
        this.form.itemId=obj.itemId
        this.form.itemCode=obj.itemCode
        this.form.itemName=obj.itemName
        this.form.specification=obj.specification
        this.form.unitOfMeasure=obj.unitOfMeasure

      }
    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj){
      if(obj !=null){
        this.form.toWarehouseId = obj[0];
        this.form.toWarehouseCode=this.warehouseOptions.find(w => w.pId == obj[0]).warehouseCode;
        this.form.toWarehouseName=this.warehouseOptions.find(w => w.pId == obj[0]).pName;
        this.form.toLocationId = obj[1];
        this.form.toLocationCode=this.warehouseOptions.find(w => w.pId == obj[0]).children.find(l => l.pId == obj[1]).locationCode;
        this.form.toLocationName=this.warehouseOptions.find(w => w.pId == obj[0]).children.find(l => l.pId == obj[1]).pName;
        this.form.toAreaId = obj[2];
        this.form.toAreaCode=this.warehouseOptions.find(w => w.pId == obj[0]).children.find(l => l.pId == obj[1]).children.find(a => a.pId == obj[2]).areaCode;
        this.form.toAreaName=this.warehouseOptions.find(w => w.pId == obj[0]).children.find(l => l.pId == obj[1]).children.find(a => a.pId == obj[2]).pName;
        console.log("hhhhhhhhh",obj)
        console.log("hhhhhhhhh11111111111",this.form.toLocationId)
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        transferId: null,        transferCode: null,        transferName: null,        transferType: null,
        salesOrderId: null,        salesOrderCode: null,        salesOrderLineId: null,        clientId: null,
        clientCode: null,        clientName: null,        itemId: null,        itemCode: null,        itemName: null,
        carrier: null,        bookingNote: null,        carNumber: null,        clientAddress: null,
        toWarehouseId: null,        toWarehouseCode: null,        toWarehouseName: null,
        toLocationId:null, toLocationCode:null, toLocationName:null, toAreaId:null, toAreaCode:null, toAreaName:null,
        transferDate: new Date().toISOString().split('T')[0],
        status: 'PREPARE',        remark: null,        attr1: null,        attr2: null,        attr3: null,        attr4: null,        createBy: null,        createByName: null,        createTime: null,        updateBy: null,        updateTime: null,        tenantId: null      };
      this.resetForm("form");
      this.warehouseInfo=[]
      this.toWareLoactionAreaInfo=null
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.transferId)
      this.codes=selection.map(item => item.transferCode)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('CLIENT_TRANFER_CODE').then(response =>{
        this.form.transferCode = response;
        this.open = true;
        this.title = "添加客户调拨";
        this.optType='add'
      });

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const transferId = row.transferId || this.ids
      getTransferclient(transferId).then(response => {
        this.form = response.data;
        this.warehouseInfo=[response.data.toWarehouseId,response.data.toLocationId,response.data.toAreaId]
        this.toWareLoactionAreaInfo={
          toWarehouseId: response.data.toWarehouseId, toWarehouseCode: response.data.toWarehouseCode,toWarehouseName: response.data.toWarehouseName,
          toLocationId:response.data.toLocationId, toLocationCode:response.data.toLocationCode, toLocationName:response.data.toLocationName,
          toAreaId:response.data.toAreaId, toAreaCode:response.data.toAreaCode, toAreaName:response.data.toAreaName
        }
        this.open = true;
        this.title = "修改客户调拨";
        this.optType="edit"

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.transferId != null) {
            const lineList = this.$refs.line.transferlineList;
            console.log("subbbbbb",lineList)
            this.form.transferLineClientList=lineList
            updateTransferclient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTransferclient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const transferIds = row.transferId || this.ids;
      const transferCodes=this.codes
      this.$modal.confirm('是否确认删除客户调拨编号为"' + transferCodes + '"的数据项？').then(function() {
        return delTransferclient(transferIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    getWarehouseList() {
      getTreeList().then(response => {
        if (response.data) {
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode.indexOf('VIR') == -1;
          });
          ;
        }
        this.warehouseOptions.map(w => {
          w.children.map(l => {
            let lstr = JSON.stringify(l.children).replace(/locationId/g, 'lId').replace(/areaId/g, 'pId').replace(/areaName/g, 'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g, 'wId').replace(/locationId/g, 'pId').replace(/locationName/g, 'pName');
          w.children = JSON.parse(wstr);

        });
        let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g, 'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/transferclient/export', {
        ...this.queryParams
      }, `transferclient_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
